package com.leyou.auth.schedule;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * User: ycs
 * Date: 2020/9/2
 * Time: 19:26
 * Description: 定时获取 token
 *
 * @author: ycs
 */
@Slf4j
@Component
public class AppTokenSchedule {
    /**
     * 刷新token的时间(24小时)
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * 获取失败重试时间(10分钟)
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 存储token
     */
    private String token;

    /**
     * 访问其他微服务的凭证
     */
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AuthService authService;
    @Scheduled(fixedRate =TOKEN_REFRESH_INTERVAL)
    public void autoAppAuth() {
        while (true) {
            try {
                String token = authService
                        .authorization(jwtProperties.getApp().getId(), jwtProperties.getApp().getServiceName());
                this.token = token;
                //获取成功
                break;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[{}服务]获取token失败!!10秒钟后重试",jwtProperties.getApp().getServiceName());
            }
            //获取失败
            try {
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public String getToken() {
        return token;
    }
}
